package com.sinochem.sales.service.controller;

import com.google.code.kaptcha.Producer;
import com.sinochem.sales.common.api.to.sms.SendSmsTo;
import com.sinochem.sales.common.api.vo.AppVersionsVO;
import com.sinochem.sales.common.api.vo.SendSmsinfoVO;
import com.sinochem.sales.common.constant.CacheConstant;
import com.sinochem.sales.common.constant.MqQueueConstant;
import com.sinochem.sales.common.constant.SecurityConstants;
import com.sinochem.sales.common.entity.Result;
import com.sinochem.sales.common.util.AssertUtils;
import com.sinochem.sales.service.service.IAppVersionsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/5/14 16:06
 * @project parent
 * @description
 * @Modification Date: 2018/5/14 16:06  {填写修改说明}
 */
@Api(tags = "未登陆方法")
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private Producer producer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IAppVersionsService appVersionsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 生成图形验证码
     */
    @ApiOperation(value = "生成图形验证码", notes = "生成图形验证码")
    @GetMapping("getImageCode")
    public Result<Map> createCode(HttpServletResponse response)
            throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        String uuid = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(text);
        redisTemplate.opsForValue().set(SecurityConstants.IMG_CODE_KEY + uuid + text, text, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
        Map<String, Object> map = new HashMap<>();
        map.put("byte", "data:image/jpg;base64," + convertImageToBase64(image));
        map.put("token", uuid);
        return Result.success(map);
    }

    /**
     * 图片转化成Base64字符串
     */
    private static String convertImageToBase64(BufferedImage image) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] data;
        try {
            ImageIO.write(image, "JPEG", bos);
            data = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("图片转化成byte[]失败");
        } finally {
            IOUtils.closeQuietly(bos);
        }
        // Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字符串
        return encoder.encode(data);
    }

    /**
     * 短信验证码
     *
     * @param sendSmsTo
     * @return
     */
    @PostMapping(value = "sendSMSCode")
    public Result<String> sendSMSCode(@RequestBody SendSmsTo sendSmsTo) {
        String re = (String) redisTemplate.opsForValue().get(CacheConstant.SEND_CODE_KEY + sendSmsTo.getMobile());
        AssertUtils.notBlank(re, "验证码未使用");
        String text = (String) redisTemplate.opsForValue().get(SecurityConstants.IMG_CODE_KEY + sendSmsTo.getToken() + sendSmsTo.getText());
        AssertUtils.notBlank(text, "验证码失效");
        AssertUtils.equals(text, sendSmsTo.getText(), "验证码错误");
        SendSmsinfoVO sendSmsinfoVO = new SendSmsinfoVO();
        sendSmsinfoVO.setMobile(sendSmsTo.getMobile());
        //TODO 设置模板
        rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE, sendSmsinfoVO);
        redisTemplate.opsForValue().set(CacheConstant.SEND_CODE_KEY + sendSmsTo.getMobile(), text, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
        return Result.success("发送短信成功");
    }


    /**
     * app版本
     *
     * @param type
     * @return
     */
    @GetMapping("findByType")

    public Result<AppVersionsVO> findByType(@RequestParam("type") String type) throws Exception {
        AppVersionsVO appVersionsVO = appVersionsService.findByType(type);
        if (appVersionsVO != null) {
            return Result.success(appVersionsVO);
        }
        return Result.error();
    }
}
